#pragma once
#include <iostream>
#include <pthread.h>
using namespace std;

namespace MutexModule
{
    class Mutex
    {
    public:
        //将拷贝构造和赋值拷贝函数给禁用
        Mutex(const Mutex&) = delete;
        const Mutex& operator=(const Mutex&) = delete;
        //构造函数
        Mutex()
        {
            int n = pthread_mutex_init(&_lock,nullptr);
            if(n != 0)
            {
                cerr<<"pthread_mutex_init"<<endl;
                return;
            }
        }
        //加锁
        void lock()
        {
            int n = pthread_mutex_lock(&_lock);
            if(n != 0)
            {
                cerr<<"pthread_mutex_lock"<<endl;
                return;
            }
        }
        pthread_mutex_t* LockPtr(){return &_lock;}
        //解锁
        void unlock()
        {
            int n = pthread_mutex_unlock(&_lock);
            if(n != 0)
            {
                cerr<<"pthread_mutex_unlock"<<endl;
                return;
            }
        }
        //析构函数
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_lock);
            if(n != 0)
            {
                cerr<<"pthread_mutex_destroy"<<endl;
                return;
            }
        }
    private:
        pthread_mutex_t _lock;
    };

    class LockGuard
    {
    public:
        //构造函数
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.lock();
        }
        ~LockGuard()
        {
            _mtx.unlock();
        }
    private:
        //锁是不能拷贝的，所以加上引用
        Mutex &_mtx;
    };
}